package com.locohamster.base;

import java.util.Random;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class CommentsAdding extends Activity implements OnClickListener {

	private Button Addbutton;
	private Button Delbutton;
	private ListView lstView;
	private CommentsDbAdapter db;
	String[] comments = new String[] { "Cooal", "Very nice", "Hate it" };
	String[] from = new String[] { CommentsDbAdapter.KEY_COMMENT };
	int[] to = new int[] { android.R.id.text1 };
	private Cursor c;
	private SimpleCursorAdapter adapter;
	private EditText editText;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Addbutton = (Button) findViewById(R.id.add);
		Addbutton.setOnClickListener(this);

		Delbutton = (Button) findViewById(R.id.delete);
		Delbutton.setOnClickListener(this);
		lstView = (ListView) findViewById(R.id.list);
		editText = (EditText)findViewById(R.id.editText1);

		// Define the columns of the table
		// which should be used in the ListView

		// Define the view elements to which the
		// columns will be mapped

		db = new CommentsDbAdapter(this);
		db.open();

		c = db.fetchAllComments();
		startManagingCursor(c);
		// Use the SimpleCursorAdapter to show the

		adapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_2, c, from, to);

		lstView.setAdapter(adapter);

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add:
			add();

			break;
		case R.id.delete:
			db.deleteComments();
			update();

			Log.v("Cosmo", "Deletwe");
			break;
		default:
			break;
		}

	}

	private void add() {
		String text = editText.getText().toString();
		if ("".equals(text)) {
			int nextInt = new Random().nextInt(3);
			db.createComment(comments[nextInt]);
		}
		else {
			db.createComment(text);
			editText.setText("");
			}
		update();
		Log.v("Cosmo", "Mam tyle pozycji: " + lstView.getCount());
		Log.v("Cosmo", "Add");

	}

	private void update() {
		adapter.changeCursor(db.fetchAllComments());

	}

	@Override
	protected void onPause() {
		db.close();
		Log.v("Cosmo", "Pause");
		super.onPause();
	}

	@Override
	protected void onResume() {
		db.open();
		Log.v("Cosmo", "Resume");
		super.onResume();
	}

}
